#!/sbin/openrc-run
# Copyright (c) 2009 Roy Marples <roy@marples.name>
# All rights reserved. Released under the 2-clause BSD license.
supervisor=supervise-daemon

name="WPA Supplicant"
description="Wi-Fi Protected Access client and IEEE 802.1X supplicant"

command=/sbin/wpa_supplicant
wpa_supplicant_if=${wpa_supplicant_if:+-i}$wpa_supplicant_if
command_args="$wpa_supplicant_args $wpa_supplicant_if"

default_conf=/etc/wpa_supplicant/wpa_supplicant.conf

depend() {
	need localmount
	use logger dbus
	after bootmisc modules entropy udev-settle
	before dns dhcpcd net
	keyword -shutdown
	provide wlan
}

find_wireless() {
	local iface=
	for iface in /sys/class/net/*; do
		if [ -e "$iface"/wireless -o -e "$iface"/phy80211 ]; then
			echo "${iface##*/}"
			return 0
		fi
	done

	return 1
}

append_wireless() {
	local iface= i=

	iface=$(find_wireless)
	if [ -n "$iface" ]; then
		for i in $iface; do
			command_args="$command_args -i$i"
		done
	else
		eerror "Could not find a wireless interface"
	fi
}

start_pre() {
	case " $command_args" in
	*" -i"*) ;;
	*) append_wireless;;
	esac

	# set default conf if dbus is explicitly disabled
	if [ -n "${wpa_supplicant_dbus}" ] && ! yesno "${wpa_supplicant_dbus}"; then
		: ${wpa_supplicant_conf:=${default_conf}}
	fi

	# use default conf if it exists
	if [ -f "${default_conf}" ]; then
		: ${wpa_supplicant_conf:=${default_conf}}
	fi

	# enable default dbus if we still dont have a config
	if [ -z "${wpa_supplicant_conf}" ]; then
		: ${wpa_supplicant_dbus:=yes}
	else
		command_args="${command_args} -c$wpa_supplicant_conf"
	fi
	case " ${command_args}" in
	*" -u"*);;
	*)	if yesno "{wpa_supplicant_dbus}"; then
			command_args="-u ${command_args}"
		fi
		;;
	esac

    checkpath -d -m 0755 -o root:root /var/run/wpa_supplicant
}
